﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Bzzb.Controllers
{
    public class DepartmentPermissionController : BaseController
    {
        private readonly ILogger<DepartmentPermissionController> _logger;
        public DepartmentPermissionController(ILogger<DepartmentPermissionController> logger, IFreeSql fsql) : base(fsql)
        {
            this._logger = logger;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] long dpid)
        {
            List<long> pmids = await _fsql.Select<DepartmentPermission>().Where(dptp => dptp.Dpid == dpid).ToListAsync(dptp => dptp.Pmid);
            _logger.LogInformation(_fsql.Select<DepartmentPermission>().Where(dptp => dptp.Dpid == dpid).ToSql(dptp => dptp.Pmid));
            return RenderJson(data: pmids);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] long dpid, [FromForm] long[] pmids)
        {
            int affrows = -1;
            _fsql.Transaction(() => {
                // 先清空之前所有角色权限
                affrows = _fsql.Delete<DepartmentPermission>().Where(dptp => dptp.Dpid == dpid).ExecuteAffrows();

                List<DepartmentPermission> dptPermissions = new();
                foreach (long pmid in pmids)
                {
                    dptPermissions.Add(new DepartmentPermission { Dpid = dpid, Pmid = pmid });
                }
                affrows = _fsql.Insert(dptPermissions).ExecuteAffrows();
            });

            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long dpid, [FromForm] long pmid)
        {
            int affrows = await _fsql.Delete<DepartmentPermission>().Where(dpp => dpp.Dpid == dpid && dpp.Pmid == pmid).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }
    }
}
